import os
from PIL import Image


class ImageConverter:
    """图片转换器"""
    
    def __init__(self):
        pass
    
    def _validate_dimensions(self, width, height, media_type="图片文件"):
        """验证尺寸是否满足要求"""
        if width < 720 or height < 1280:
            raise Exception(f"{media_type}清晰度不够，宽度：{width}，高度：{height}")

    def _calculate_crop_params(self, width, height, target_w=1080, target_h=1920):
        """计算裁剪参数"""
        # 计算缩放比例，短边对齐
        scale_w = target_w / width
        scale_h = target_h / height
        scale = max(scale_w, scale_h)  # 确保短边对齐

        # 计算缩放后尺寸
        new_w = int(width * scale)
        new_h = int(height * scale)

        # 计算裁剪起点，居中裁剪
        crop_x = max(0, (new_w - target_w) // 2)
        crop_y = max(0, (new_h - target_h) // 2)

        return new_w, new_h, crop_x, crop_y

    def _get_output_path(self, input_path, suffix="_converted", extension=None):
        """生成输出文件路径"""
        base, ext = os.path.splitext(input_path)
        if extension:
            ext = f".{extension}"
        return f"{base}{suffix}{ext}"

    def convert_image(self, input_path, output_format="jpg"):
        """转换图片文件"""
        try:
            with Image.open(input_path) as img:
                width, height = img.size

                # 验证尺寸
                self._validate_dimensions(width, height, "图片")

                # 计算裁剪参数
                new_w, new_h, crop_x, crop_y = self._calculate_crop_params(width, height)
                target_w, target_h = 1080, 1920

                # 缩放图片
                img = img.resize((new_w, new_h), Image.Resampling.LANCZOS)

                # 裁剪图片
                img = img.crop((crop_x, crop_y, crop_x + target_w, crop_y + target_h))

                # 输出文件路径
                output_file = self._get_output_path(input_path, extension=output_format.lower())

                # 根据格式保存图片
                if output_format.lower() == "jpg":
                    img = img.convert("RGB")  # 确保是RGB模式
                    img.save(output_file, "JPEG", quality=95)
                else:
                    img.save(output_file, output_format.upper())

                return output_file

        except Exception as e:
            raise Exception(f"转换失败，错误信息：\n{e}")